package me.skyun.androidarch.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import me.skyun.androidarch.R;

/**
 * Created by linyun on 16/11/17.
 */
public abstract class BaseTabActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_tab);

        ViewPager viewPager = (ViewPager) findViewById(R.id.base_tab_view_pager);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.base_tab_tab_layout);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        viewPager.setAdapter(new _FragmentPagerAdapter(getSupportFragmentManager()));

        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
    }

    private class _FragmentPagerAdapter extends FragmentPagerAdapter {

        public _FragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return BaseTabActivity.this.getFragment(position);
        }

        @Override
        public int getCount() {
            return BaseTabActivity.this.getTabCount();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return BaseTabActivity.this.getPageTitle(position);
        }
    }

    protected abstract Fragment getFragment(int position);

    protected abstract int getTabCount();

    protected abstract CharSequence getPageTitle(int position);
}
